#include "multimediaRegister.h"

bool multimediaCompare(multimedia *m1, multimedia *m2){
	if (m1->getName() == m2->getName()){
		return m1->getYear() < m2->getYear();
	}
	else{
		return m1->getName() < m2->getName();
	}
}

multimediaRegister::multimediaRegister()
{
}


multimediaRegister::~multimediaRegister()
{
}

void multimediaRegister::add(multimedia *m){
	v.push_back(m);
}

void multimediaRegister::remove(multimedia *m){
	vector<multimedia*>::iterator it = search(m);
	if (it != v.end()){
		delete *it;
		v.erase(it);
		cout << "Entry removed successfully!" << endl;
	}
	else{
		cout << "Entry does not exist!" << endl;
	}
	_sleep(1000);
}

vector<multimedia*>::iterator multimediaRegister::search(multimedia *m){
	vector<multimedia*>::iterator it = find(v.begin(), v.end(), m);
	return it;
}

void multimediaRegister::sort(){
	std::sort(v.begin(), v.end(), multimediaCompare);
}

void multimediaRegister::display(){
	for (auto it = v.begin(); it < v.end(); it++)
	{
		(**it).print();
		cout << **it << endl;
	}
}

void multimediaRegister::readFile(string f){
	string line;
	istringstream iss;
	ifstream in(f);
	v.clear();
	while (getline(in, line, ';')){
		if (line == "multimedia"){
			multimedia *m = new multimedia();
			in >> *m;
			v.push_back(m);
		}
		else if (line == "music"){
			music *m = new music();
			in >> *m;
			v.push_back(m);
		}
		else if (line == "movie"){
			movie *m = new movie();
			in >> *m;
			v.push_back(m);
		}
		else if (line == "book"){
			book *b = new book();
			in >> *b;
			v.push_back(b);
		}
	}
}

void multimediaRegister::writeFile(string f){
	ofstream out(f);
	for (auto it = v.begin(); it < v.end(); it++){
		out << **it << endl;
	}
}